package com.kpijavatraining6.module2.mainMenu;

import com.kpijavatraining6.module2.*;
import com.kpijavatraining6.module2.actionTools.Loader;
import com.kpijavatraining6.module2.actionTools.TestStep;
import com.kpijavatraining6.module2.actionTools.UserAction;
import com.kpijavatraining6.module2.actionTools.XMLoader;
import com.kpijavatraining6.module2.questions.QuestionStructure;
import com.kpijavatraining6.module2.questions.Reader;
import com.kpijavatraining6.module2.questions.UserAnswer;
import com.kpijavatraining6.module2.sessionTools.*;

import java.io.*;
import java.util.*;

public class GameLogic {
    private String userName;
    private History history;
    private boolean isSessionWasInterrupted = false;
    public final int TEST_LENGT = 10;
    int questionLevel = 1;
    private ScannerOfInput scanner = new ScannerOfInput();

    Map<QuestionStructure, Boolean> questionsEntry;

    public GameLogic(String name) {
        userName = name;
        Loader loader = new Loader(userName);
        history = loader.loadHistory();
        if (history.getCurrentNumber() > 0) {
            isSessionWasInterrupted = true;
        }
    }

    public void runGameLogic() {
       XMLoader reader;
        if (isSessionWasInterrupted) {
            reader = new XMLoader();
        } else {
            reader = new XMLoader();
        }
        runInterview(reader.parse("java_questions.xml"));
    }

    /**
     * runLogic runs main game logic
     */
    public void runInterview(ArrayList<QuestionStructure> questionStructures) {
        questionsEntry = createQuestionEntry(questionStructures);
        if (!isSessionWasInterrupted) {
            Collections.shuffle(questionStructures);
        }
        for (int i = 0; i < TEST_LENGT; i++) {
            System.out.println(i);
            poolling();
            if(i == 8){
               questionLevel = new LevelChecker().check(history.getTestStepArr());
            }
        }
        endTest();
    }


    private boolean poolling() {
        String userAnswer;
        for (QuestionStructure question : questionsEntry.keySet()) {
            if (question.getQuestionLevel() == questionLevel) {
                if (questionsEntry.get(question)) {
                    System.out.println("questionLvl = " + question.getQuestionLevel());
                    question.printQuestion();
                    questionsEntry.put(question, new Boolean(false));
                    userAnswer = scanner.inputScanner();
                    workWithAnswer(userAnswer, question);
                    //TODO usersAnswer!!!!!
                    return true;
                }
            }
        }
        return false;
    }

    private void workWithAnswer(String userAnswer, QuestionStructure question) {
        UserAction userAction = new UserAction(history, userName);
        if (userAction.isNewAction(userAnswer)) {
            userAction.newAction(userAnswer);
        } else {
            TestStep testStep = new TestStep(question, userAnswer);
            history.push(testStep);
            System.out.printf("You've selected - %s\n", userAnswer);
        }
    }

    private Map<QuestionStructure, Boolean> createQuestionEntry(ArrayList<QuestionStructure> questionStructures) {
        Map<QuestionStructure, Boolean> questions = new HashMap<QuestionStructure, Boolean>();
        for (QuestionStructure question : questionStructures) {
            questions.put(question, true);
        }
        return questions;
    }

    private void endTest() {
        int score = countScore();
        System.out.printf("Your score:%d\n", score);
        UserStatistics userStatistics = new UserStatistics(userName, score, TEST_LENGT);
        userStatistics.saveStatistic();
        cleanUserHistory();
    }


    /**
     * cleaning file with user`s session data;
     */
    private void cleanUserHistory() {
        try {
            FileWriter fstream = new FileWriter(userName + ".txt");
            BufferedWriter out = new BufferedWriter(fstream);
            out.write("");
            out.close();
        } catch (Exception e) {
            System.err.println("Error in file cleaning: ");

        }
    }

    public void printMethod(int i, ArrayList<QuestionStructure> questionStructures) {

    }

    /**
     * countScore used for count of right answers chosen by user
     * (!) it will clean your current history
     *
     * @return
     */
    public int countScore() {
        int count = 0;
        while (history.isRollBackPossible()) {
            TestStep testStep = history.pull();
            if (testStep.isRightAnswer()) {
                count++;
            }
        }
        return count;
    }
}
